package tech.jabari.user.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import tech.jabari.base.BaseResponse;
import tech.jabari.utils.FileUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 下载文件。
 * @author Jabari Lu
 * @title: UploadServlet
 * @data 2020/8/14 13:34
 */
@WebServlet("/download.action")
public class DownloadServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //带UUID的文件名
        String fileUUIDName = request.getParameter("fileName");
        String fileName = fileUUIDName;//FileUtils.extractFileName(fileUUIDName);
        System.out.println(fileName);

        String fileRoot = this.getServletContext().getRealPath("/upload");

        //根据文件名找到存储目录
        String fileDir = fileRoot ; //FileUtils.fileSave(fileUUIDName, fileRoot);

        String targetFileUrl = fileDir + File.separator + fileUUIDName;
        System.out.println(targetFileUrl);
        File file = new File(targetFileUrl);

        if (!file.exists()) {
            System.out.println("..........下载的目标文件不存在!");
            return;
        }

        response.setHeader("content-disposition",
                "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

        FileInputStream inputStream = new FileInputStream(file);
        ServletOutputStream servletOutputStream = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) > 0) {
            servletOutputStream.write(buffer, 0, len);
        }
        inputStream.close();
        servletOutputStream.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }
}
